import { createRouter, createWebHistory } from 'vue-router';
import AdminLogin from '../views/AdminLogin.vue';
import AdminView from '../views/AdminView.vue';
import Dashboard from '../views/admin/Dashboard.vue';
import Users from '../views/admin/Users.vue';
import Regions from '../views/admin/Regions.vue';
import ScenicSpots from '../views/admin/ScenicSpots.vue';

// 路由配置
const routes = [
  {
    path: '/admin/login',
    name: 'AdminLogin',
    component: AdminLogin,
    meta: { requiresAuth: false }
  },
  {
    path: '/admin',
    name: 'AdminView',
    component: AdminView,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表盘' }
      },
      {
        path: 'users',
        name: 'Users',
        component: Users,
        meta: { title: '用户管理' }
      },
      {
        path: 'regions',
        name: 'Regions',
        component: Regions,
        meta: { title: '地区管理' }
      },
      {
        path: 'scenic-spots',
        name: 'ScenicSpots',
        component: ScenicSpots,
        meta: { title: '景点管理' }
      },
      // 可以根据需要添加更多管理页面路由
    ]
  }
];

// 创建路由实例
const adminRouter = createRouter({
  history: createWebHistory('/'),
  routes
});

// 路由守卫
adminRouter.beforeEach((to, from, next) => {
  // 检查是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 获取登录状态
    const isLoggedIn = localStorage.getItem('adminLoggedIn') === 'true';
    
    if (!isLoggedIn) {
      // 未登录，重定向到登录页
      next({
        path: '/admin/login',
        query: { redirect: to.fullPath }
      });
    } else {
      // 已登录，继续导航
      next();
    }
  } else {
    // 不需要认证的页面，直接导航
    next();
  }
});

export default adminRouter;